package phone.qyg.com.qyg.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.OpenLocalMapUtil;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.BusInfo;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.MassTransitRoutePlanOption;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.cocosw.bottomsheet.BottomSheet;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.baidu.LineActivity;
import phone.qyg.com.qyg.adapter.FitnessLineAdapter;
import phone.qyg.com.qyg.model.baidu.LineInfo;
import phone.qyg.com.qyg.model.baidu.TranInfo;

//import com.cocosw.bottomsheet.BottomSheet;


/**
 * 作者：lblbh on 2017/6/6 14:46
 * 邮箱：lanbuhan@163.com
 * 功能：现在线路搜索
 */
@ContentView(R.layout.fintness_line_map)
public class FintnessLineMapActivity extends BaseActivity {

    String TRANSIT = "transit";
    String DRIVE = "drive";
    String LINE_TYPE = TRANSIT;

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.host)
    TextView host;

    @ViewInject(R.id.termini)
    TextView termini;

    @ViewInject(R.id.one_key)
    TextView one_key;

    @ViewInject(R.id.one_hint)
    View one_hint;

    @ViewInject(R.id.two_key)
    TextView two_key;

    @ViewInject(R.id.two_hint)
    View two_hint;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    TranInfo tranInfo;

    RoutePlanSearch mSearch;

    RoutePlanSearch mSearch1;

    BaseViewStateLayout baseViewLayout;

    RecyclerView recycler;

    int type;

    List<LineInfo> lineDrivingInfos;

    List<LineInfo> lineMassTransitInfos;

    double cureentLatitude;
    double cureentLongitude;

    PlanNode tranEndNode;
    PlanNode tranStarNode;

    boolean isUpdateLatLng;//修改地址状态

    LatLng updateLatLng;//修改地址

    @Override
    public void initSucessView() {
        tranInfo = (TranInfo) getTransModels();
        type = tranInfo.type;


        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener( routeListener );
        mSearch1 = RoutePlanSearch.newInstance();
        mSearch1.setOnGetRoutePlanResultListener( routeListener );
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        cureentLatitude = tranInfo.cureentLatitude;
        cureentLongitude = tranInfo.cureentLongitude;
        ////0--到这里去 1-从这里出发
        if(type == 1){
            host.setText(tranInfo.address);
            termini.setText((isRequestStr(tranInfo.currentAddress)?tranInfo.currentAddress:getString(R.string.my_host_hint)));
        }else{
            termini.setText(tranInfo.address);
            host.setText((isRequestStr(tranInfo.currentAddress)?tranInfo.currentAddress:getString(R.string.my_host_hint)));
        }

        if(cureentLatitude >0){
            PlanNode enNode = PlanNode.withLocation(new LatLng(cureentLatitude,cureentLongitude));
            PlanNode stNode = PlanNode.withLocation(new LatLng(tranInfo.latitude,tranInfo.longitude));

            setStartPlanAndEndPlan(stNode,enNode);
        }
    }


    @Event(value = {R.id.back,R.id.one_key,R.id.two_key,R.id.termini,R.id.host})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.one_key:
            case R.id.two_key:
                updateTitleState(v);
                break;
            case R.id.termini:
                if(type == 0){
                    return;
                }
                //选择目的地地址
                TransformController.transformControllerTypeForResult(FintnessLineMapActivity.this,FindAddressActivity.class,1);
                break;
            case R.id.host:
                if(type == 1){
                    return;
                }
                TransformController.transformControllerTypeForResult(FintnessLineMapActivity.this,FindAddressActivity.class,1);
                break;

        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                SuggestionResult.SuggestionInfo suggestionInfo = data.getParcelableExtra(ApplicationConfig.APP_INFO_TRANS);
                /**
                 * LatLng hmPos = new LatLng(latitude, longitude);// 坐标
                 */
//                PlanNode stNode = PlanNode.withLocation(new LatLng(Double.valueOf(fitnessMap.latitude),Double.valueOf(fitnessMap.longitude)));
//                PlanNode enNode = PlanNode.withLocation(suggestionInfo.pt);

                if(type == 0){
                    host.setText(suggestionInfo.key);
                }else{
                    termini.setText(suggestionInfo.key);
                }

//                String cityCode = SharePrefUtil.getString(SharePrefUtil.KEY.CITY_CODE,null);
//                City city = JSONTool.requestJSONClazz(cityCode, City.class);
//                String title = "";
//                if(city != null){
//                    title = city.title;
//                }

//                isUpdateLatLng = true;

                updateLatLng = new LatLng(tranInfo.latitude,tranInfo.longitude);

                PlanNode enNode = null;
                PlanNode stNode = PlanNode.withLocation(updateLatLng);
                if(suggestionInfo.pt != null){
                    enNode = PlanNode.withLocation(suggestionInfo.pt);
                }else{
                    SystemPrintl.systemPrintl("使用默认城市 ----->>>呼和浩特");
                    String city = SharePrefUtil.getString(SharePrefUtil.KEY.CITY,ApplicationConfig.CITY);
                    enNode  = PlanNode.withCityNameAndPlaceName(city,suggestionInfo.key);
                }


//                SystemPrintl.systemPrintl("坐标--latitude ->"+suggestionInfo.pt.latitude+",longitude-->"+suggestionInfo.pt.longitude);

                setStartPlanAndEndPlan(stNode,enNode);

                break;
            default:
                break;
        }
    }

    private void setStartPlanAndEndPlan(PlanNode stNode, PlanNode enNode){
        if(type == 1){
            //从这里出发
            tranStarNode = stNode;
            tranEndNode = enNode;
            //公交
            mSearch.masstransitSearch(new MassTransitRoutePlanOption().from(stNode).to(enNode));

            //驾车
            mSearch1.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(enNode));
        }else{
            //到这里去
            tranStarNode = enNode;
            tranEndNode = stNode;
            //公交
            mSearch.masstransitSearch(new MassTransitRoutePlanOption().from(enNode).to(stNode));

            //驾车
            mSearch1.drivingSearch(new DrivingRoutePlanOption().from(enNode).to(stNode));
        }
    }

    OnGetRoutePlanResultListener routeListener = new OnGetRoutePlanResultListener(){
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult result) {
            //获取跨城综合公共交通线路规划结果
            List<MassTransitRouteLine> routeLines = result.getRouteLines();

            lineMassTransitInfos = new ArrayList<LineInfo>();

            if(!isRequestList(routeLines) && LINE_TYPE == TRANSIT){
                PromptManager.showToast(R.string.find_map_transit_empty);
                return;
            }

            if(!isRequestList(routeLines)){
                return;
            }


            for (int i =0,j=routeLines.size();i<j;i++){
                MassTransitRouteLine line = routeLines.get(i);
                /**
                 *   int distance;      //距离（单位：米）
                 int duration;      //耗时 (单位：秒)
                 String arriveTime; //本线路预计到达时间：格式举例：2016-09-29 13:48:00
                 double price;      //本线路价格（元）
                 List<PriceInfo> priceInfo;       //票价详情（起终点为大陆地区同城时，此字段有值；其他情况，此字段为空）
                 List<List<TransitStep>> newSteps; //一条线路中的步骤（step）
                 */
                int distance = line.getDistance();
                int duration = line.getDuration();

                //步数
                int walk = 0;
                //车站名称
                StringBuffer stationName = new StringBuffer("");
                //详细信息描述
                List<String> lineDetail = new ArrayList<String>();
                List<List<MassTransitRouteLine.TransitStep>> lineStep = line.getNewSteps();//getNewSteps

                int item_line_count =0;
                for (int z=0,q=lineStep.size();z<q;z++){
                    //到这里就是一条线路 开始

                    //这里标记线路index 做对比使用
                    item_line_count = z;

                    //这个集合是 A-B 多种情况
                    List<MassTransitRouteLine.TransitStep> steps = lineStep.get(z);

                    for (int a=0,s=steps.size();a<s;a++){
                        MassTransitRouteLine.TransitStep sitStep = steps.get(a);

                        //在a-b都有多种情况下 会存在instruction 等于空
                        if(a == 0)
                            lineDetail.add(sitStep.getInstructions());

                        BusInfo busInfo = sitStep.getBusInfo();

                        if(busInfo == null){
                            //只有当它等于空 步数才是有意义
                            //添加步数累加 统计步数距离
                            walk +=sitStep.getDistance();
                        }else{

                            //一条线路 需要换成
                            if(z>0 && stationName.length()>0 && (a == 0))
                                stationName.append(" - ");

                            //当a大于证明一条线路 有多种选择
                            if(a>0 && stationName.length()>0)
                                stationName.append("/");
                            stationName.append(busInfo.getName());
                        }

                    }
                }

                LineInfo lineInfo= new LineInfo();
                lineInfo.distance = line.getDistance();
                lineInfo.duration = line.getDuration();
                lineInfo.walk = walk;
                lineInfo.lineDetail = lineDetail;
                lineInfo.line_name = stationName.toString();
//                lineInfo.massTransitRouteLine = line;
                lineInfo.type = 0;
                lineInfo.tranEndNode =tranEndNode;
                lineInfo.tranStarNode =tranStarNode;
                lineMassTransitInfos.add(lineInfo);
            }
            CommonUtil.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if(LINE_TYPE == TRANSIT)
                        setRecycler(lineMassTransitInfos,true);
                }
            });


        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                //获取驾车线路规划结果
            List<DrivingRouteLine> routeDrivingLines = drivingRouteResult.getRouteLines();

            if(!isRequestList(routeDrivingLines) && (LINE_TYPE == DRIVE)){
                PromptManager.showToast(R.string.find_map_driving_empty);
                return;
            }

            if(!isRequestList(routeDrivingLines)){
                return;
            }

            lineDrivingInfos = new ArrayList<LineInfo>();


            for (int i =0,j=routeDrivingLines.size();i<j;i++){
                DrivingRouteLine line = routeDrivingLines.get(i);

                int distance = line.getDistance();
                int duration = line.getDuration();

                List<DrivingRouteLine.DrivingStep> steps = line.getAllStep();

                //详细信息描述
                List<String> lineDetail = new ArrayList<String>();
                for (int a=0,z=steps.size();a<z;a++){
                    DrivingRouteLine.DrivingStep step = steps.get(a);

                    //获取描述信息
                    String instructions = step.getInstructions();

                    //添加描述信息
                    lineDetail.add(instructions);
                }

                String title = "";
                if(i == 0){
                    title = getString(R.string.short_time);
                }else if(i == 1){
                    title = getString(R.string.short_distance);
                }else{
                    title = MessageFormat.format(getString(R.string.programme),String.valueOf(i));
                }
                LineInfo lineInfo= new LineInfo();
                lineInfo.distance = line.getDistance();
                lineInfo.duration = line.getDuration();
                lineInfo.title = title;
                lineInfo.lineDetail = lineDetail;
                lineInfo.drivingRouteLine = line;
                lineInfo.type = 1;
                lineDrivingInfos.add(lineInfo);
            }
            CommonUtil.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if(LINE_TYPE == DRIVE)
                        setRecycler(lineDrivingInfos,false);
                }
            });
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

        }
    };



    private void setRecycler(final List<LineInfo> lineInfos, final boolean isMassTransit){
        if(baseViewLayout != null){
            CommonUtil.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    setData(lineInfos,isMassTransit);
                }
            });
            return;
        }
        baseViewLayout = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_recycler, null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
//                if(adapter == null){
                    LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
                    layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
                    recycler.addItemDecoration(new RecyclerViewItemDecoration(
                            RecyclerViewItemDecoration.MODE_HORIZONTAL,
                            getResources().getColor(R.color.divider),
                            CommonUtil.dip2px(QXApplication.getContext(),1),0,0));
                    recycler.setLayoutManager(layoutVerManager);
//                }
                return sucessView;
            }

            @Override
            public Object obtionData() {
                CommonUtil.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        setData(lineInfos,isMassTransit);
                    }
                });
                return DELFAUTSTATE;
            }
        };

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseViewLayout, layoutParams);
        x.view().inject(linear);
    }

    private void setData(final List<LineInfo> lineInfos,boolean isMassTransit){

        if (!isRequestList(lineInfos)) {
            baseViewLayout.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
            baseViewLayout.stateView();
            return;
        }


        //成功获取到数据
        baseViewLayout.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
        baseViewLayout.stateView();

        if(LINE_TYPE == DRIVE){
            if(OpenLocalMapUtil.isGdMapInstalled() || OpenLocalMapUtil.isBaiduMapInstalled()){
                if(isRequestList(lineInfos) && (lineInfos.get(lineInfos.size()-1).localType ==0)){
                    LineInfo lineInfo = new LineInfo();
                    lineInfo.localType = 1;
                    lineInfos.add(lineInfo);
                }
            }
        }

        if(isMassTransit){

            final FitnessLineAdapter massTransitAdapter = new FitnessLineAdapter(QXApplication.getContext(),
                    lineInfos,
                    new FitnessLineAdapter.OnLocalHostMap() {
                        @Override
                        public void onClickLocal() {
                            //我在点击本地
                            getLocalHostApp();
                        }
                    });

            massTransitAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    // com.baidu.mapapi.search.core.b
                    LineInfo model = (LineInfo) massTransitAdapter.getDatas().get(position);
                    model.item = position;
                    if(model.localType == 0)
                        TransformController.transformControllerModel(QXApplication.getContext(), LineActivity.class,model);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });
            recycler.setAdapter(massTransitAdapter);
            massTransitAdapter.notifyDataSetChanged();
        }else{
            final FitnessLineAdapter drivingAdapter = new FitnessLineAdapter(QXApplication.getContext(),
                    lineInfos,
                    new FitnessLineAdapter.OnLocalHostMap() {
                        @Override
                        public void onClickLocal() {
                            //我在点击本地
                            getLocalHostApp();
                        }
                    });

            drivingAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    // com.baidu.mapapi.search.core.b
                    LineInfo model = (LineInfo) drivingAdapter.getDatas().get(position);
                    model.item = position;
                    if(model.localType == 0)
                        TransformController.transformControllerModel(QXApplication.getContext(), LineActivity.class,model);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });
            recycler.setAdapter(drivingAdapter);
            drivingAdapter.notifyDataSetChanged();
        }



    }

    private void getLocalHostApp(){
            BottomSheet.Builder builder = new BottomSheet
                    .Builder(this, com.cocosw.bottomsheet.R.style.BottomSheet_Dialog)
                    .title("请选择地图");

                    if(OpenLocalMapUtil.isBaiduMapInstalled())
                        builder.sheet(0, "百度地图");
                    if(OpenLocalMapUtil.isGdMapInstalled())
                        builder.sheet(1, "高德地图");

                                /**
                                 * OpenLocalMapUtil.isGdMapInstalled() || OpenLocalMapUtil.isBaiduMapInstalled()
                                 */
//if(OpenLocalMapUtil.isBaiduMapInstalled()){
//SystemPrintl.systemPrintl("我安装的百度地图");
//}
//if(OpenLocalMapUtil.isGdMapInstalled()){
//SystemPrintl.systemPrintl("我安装的高德地图");
//}
                builder.listener(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            String originLon = String.valueOf((tranInfo.type == 1) ?tranInfo.longitude : tranInfo.cureentLongitude);
                            String originLat = String.valueOf((tranInfo.type == 1) ?tranInfo.latitude : tranInfo.cureentLatitude);
                            String originName = (tranInfo.type == 1)?tranInfo.address:(isRequestStr(tranInfo.currentAddress)?tranInfo.currentAddress:getString(R.string.my_host_hint));
                            String desLon = String.valueOf((tranInfo.type == 1) ?tranInfo.cureentLongitude : tranInfo.longitude);
                            String desLat = String.valueOf((tranInfo.type == 1) ?tranInfo.cureentLatitude : tranInfo.latitude);
                            String desName = (tranInfo.type == 1)?(isRequestStr(tranInfo.currentAddress)?tranInfo.currentAddress:getString(R.string.my_host_hint)):tranInfo.address;
                            if (which == 0) {

                                SystemPrintl.systemPrintl("我在点击百度地图");
                                Intent intent = new Intent();
                                intent.setData(Uri.parse(OpenLocalMapUtil.getAppBaiduMapUri(originLon,originLat,originName,desLon,desLat,desName)));
                                startActivity(intent);
                                /**
                                 *
                                 String uri = "baidumap://map/direction?origin=latlng:%1$s,%2$s|name:%3$s&" +
                                 "destination=latlng:%4$s,%5$s|name:%6$s&mode=driving";
                                 intent.setData(Uri.parse(String.format(uri,slon, slat, sname, dlon, dlat, dname)));
                                 //                intent.setData(Uri.parse("baidumap://map/direction?origin=latlng:"+slon+","+slat+"|name:"+sname+"&destination=latlng:"+dlon+","+dlat+"|name:"+dname+"&mode=driving"));
                                 startActivity(intent);
                                 */
                            } else if(which == 1){
                                //String appName, String slat, String slon, String sname, String dlat, String dlon, String dname
                                SystemPrintl.systemPrintl("我在点击高德地图");
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_VIEW);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setPackage("com.autonavi.minimap");
                                intent.setData(Uri.parse(OpenLocalMapUtil.getAppGdMapUri("蒙享动",originLat,originLon,originName,desLat,desLon,desName)));
                                startActivity(intent);
                            }
                        }
                    }).build().show();
    }

    private void updateTitleState(View v) {

        String tempType = (v == one_key) ?TRANSIT :DRIVE;

        if(tempType.equals(LINE_TYPE))
            return;

        LINE_TYPE = tempType;

        CommonUtil.setTextViewDrawableDirection(one_key,8,(v == one_key)?R.drawable.transit_select_icon :R.drawable.transit_normal_icon);
        CommonUtil.setTextViewDrawableDirection(two_key,8,(v == two_key)?R.drawable.drive_select_icon :R.drawable.drive_normal_icon);
        one_hint.setVisibility((v == one_key)?View.VISIBLE:View.GONE);
        two_hint.setVisibility((v == two_key)?View.VISIBLE:View.GONE);


        if((LINE_TYPE == TRANSIT) && isRequestList(lineMassTransitInfos)){
            if(baseViewLayout == null){
                setRecycler(lineMassTransitInfos,true);
            }else{
                setData(lineMassTransitInfos,true);
            }

        }else if((LINE_TYPE == DRIVE) && isRequestList(lineDrivingInfos)){

            if(baseViewLayout == null){
                setRecycler(lineDrivingInfos,false);
            }else{
                setData(lineDrivingInfos,false);
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mSearch != null)
            mSearch.destroy();
    }

    @Override
    public void initViewHandler() {}
}
